<script setup lang="ts">
import CdlTable from "@/components/table";
import {useTablePagingTemplate} from "@/hooks/TableHooks";
import {reactive} from "vue";
import type {Project} from "@/interfaces/views/project/project";
import type {State, Request, Query, Mode} from "@/interfaces/components/Page"
import {TableTree} from "@/interfaces/components/Table";
import CdlSearch from "@/components/search";
import {FormTree} from "@/interfaces/components/Form";
import {useRoute, useRouter} from "vue-router";
import {appStore} from "@/store/modules/app";
import {useProjectEndApi} from "@/api/project/project";
import {ElMessageBox} from "element-plus";
import {ElMessage} from "element-plus/es";
import * as events from "events";

const router = useRouter()
const route = useRoute()
const store = appStore()
const request: Request = {
  createdIsNeed: true,
  url: "/project/project"
}

const state = reactive<State<Query<Project>, Project>>({
  queryForm: {
    projectStatus: undefined,
    createTime: undefined,
  },
  dataList: []
})
const{query, added, update, handleSizeChange, handleCurrentChange, loading} = useTablePagingTemplate(request, state)

const tabTree: TableTree<Project> = {
  colRule: [
    {ti: "订单ID", prop: "id", width: 175},
    {ti: "订单名称", prop: "name", width: 200, tooltip: true},
    {ti: "订单类型", prop: "typeId", dict: "project_type"},
    {ti: "付款方式", prop: "payMode", dict: "payment_method"},
    {ti: "关联托运人", prop: "shipperName", tooltip: true},
    {ti: "订单负责人", prop: "managerName"},
    {ti: "订单状态", prop: "projectStatus", dict: "project_state", width: 110},
    {ti: "装货地址", prop: "loadingAddress", width: 200, tooltip: true},
    {ti: "卸货地址", prop: "unloadingAddress", width: 200, tooltip: true},
    {ti: "当前任务数", prop: "taskNumber"},
    {ti: "货物名称", prop: "cargoName"},
    {ti: "货物分类代码", prop: "cargoTypeId", width:110},
    {ti: "确认任务趟次", prop: "confirmTaskCount", width:110},
    {ti: "货物毛重", prop: "cargoGrossWeight"},
    {ti: "还田效果", prop: "returnEffect"},
    {ti: "创建时间", prop: "createTime", width: 160},
    {ti: "备注", prop: "remark"},
  ],
  control: [
    {name: "详情", type: "info", prop: "id", method: jumpProjectDetail, auth: "project:project:info",
      pretreatment: (data)=> data.projectStatus !== 1},
    {name: "派发任务", type: "success", method: jumpCreateTask, auth: "project:project:sell",
      pretreatment: (data)=> data.projectStatus !== 1},
    {name: "结束", type: "danger", prop: "id", method: taskEndHandle, auth: "project:project:end",
      pretreatment: (data)=> data.projectStatus !== 1},
    {name: "完善信息", type: "primary", prop: "id", method: jumpProjectInsert, auth: "project:project:save",
      pretreatment: (data)=> data.projectStatus === 1},
  ]
}

const searTree: FormTree<Project> = [
  [
    {component: "select", options: store.getDict("project_state"), optionProps: {
        label: "dictLabel", value: "dictValue"
      }, prop: "projectStatus", label: "订单状态"},
    {component: "input", prop: "name", label: "订单名称"},
    {component: "input", prop: "managerId", label: "订单负责人"},
    {component: "datePicker", type: "daterange", prop: "createDateRange", label: "创建日期区间",
     startPlaceholder: "开始日期", endPlaceholder: "结束日期",
      defaultTime: [
          new Date(2000,1,1,0,0,0),
          new Date(2000,2, 1, 23, 59, 59)
      ]
    },
  ]
]

/**
 * 跳转项目详情
 * @param id
 */
function jumpProjectDetail(id: number | string){
  router.push({
    path: "/projectManage/project/projectList/projectDetails",
    query:{
      id: id
    }
  })
}

/**
 * 跳转新建任务
 */
function jumpCreateTask(data: Project){
  const { id, cargoName, cargoTypeId } = data
  router.push({
    path: "/projectManage/task/createAndModifyTask",
    query: {
      projectId: id,
      cargoName,
      cargoTypeId
    }
  })
}

/**
 * 跳转新建项目
 */
function jumpProjectInsert(id: string | undefined = undefined){
  router.push({
    path: "/projectManage/project/projectList/createAndModifyProject",
    query: {
      id: id,
      emit: 1
    }
  })
}
function taskEndHandle(id: string){
  ElMessageBox.confirm(
      '请确认该订单下关联的所有任务已全部结算，否则将不成功！请确认以继续?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
        useProjectEndApi(id).then(res =>{
          ElMessage({
            type: 'success',
            message: 'Delete completed',
          })
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}

/**
 * 回调处理
 * @param mode
 * @param val
 */
function popupCallBack(mode: Mode, val?: any){
  switch (mode){
    case "add":
      added(val)
          break
    case "update":
      update(val)
          break
    case "search":
      if(val.createDateRange) {
        val.st = val.createDateRange[0]
        val.et = val.createDateRange[1]
        delete val.createDateRange
      }
      query(val)
          break
    case "resetting":
      query()
          break
  }
}

</script>

<template>
  <el-card>
    <CdlSearch :model="state.queryForm" :template-tree="searTree" @submit="popupCallBack">
      <template #menu>
        <el-button @click="()=> jumpProjectInsert()" type="primary" v-auth="'project:project:save'">创建订单</el-button>
      </template>
    </CdlSearch>
    <CdlTable :template-tree="tabTree" :data="state.dataList" :control-width="280" :loading="loading" controlFixed></CdlTable>
    <el-pagination
        :current-page="state.page"
        :page-sizes="state.pageSizes!"
        :page-size="state.limit"
        :total="state.total"
        hide-on-single-page
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
  </el-card>
</template>
